//
//  EGAMainViewController.m
//  EGA_Archives_iOS
//
//  Created by Aekcachai Chokeprajugchut on 3/4/56 BE.
//  Copyright (c) 2556 EGA. All rights reserved.
//

#import "EGAMainViewController.h"
#import "EGAEmployeeInfo.h"
#import "EGAAppDelegate.h"
#import "EGAMainViewController.h" 
#import "mainEGAViewController.h" 
#import "SVPullToRefresh.h"
#import <QuartzCore/QuartzCore.h>
#import "arcAssignDetailEGAViewController.h" 
#import "ARC_DB.h"
#import "EGAUtility.h"


@interface EGAMainViewController ()<UITableViewDelegate, UITableViewDataSource>
{
   NSMutableArray
    *listOfItems;
}


@property (nonatomic, strong) NSMutableArray *dataSource;
@end


@implementation EGAMainViewController

-(EGAAppDelegate*)appDelegate

{
    
    return  (EGAAppDelegate*)[[UIApplication sharedApplication] delegate];
    
}



@synthesize arrListNewBook;
@synthesize filteredArrListNewBook;
@synthesize searchBar;
@synthesize isFiltered;


//NSArray * arrListNewBook;
NSNumber *countArr;
@synthesize  tblview;


-(void)refresh
{
    ARC_DB * DB = [[ARC_DB alloc]init];
    if([DB internetConnected])
    {
        arrListNewBook=nil;
        [arrListNewBook release];
        [DB saveNewBook:@""];
        arrListNewBook = [DB getNewBook];
    }
    else
    {
            
    }
}


-(void)pull_refresh:(NSString*)Type
{
    ARC_DB * DB = [[ARC_DB alloc]init];
    if([DB internetConnected])
    {
        arrListNewBook=nil;
        [arrListNewBook release];
        [DB saveNewBook:Type];
        arrListNewBook = [DB getNewBook];
    }
    else
    {
        
    }
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}


-(void)addPullToRefreshToTable
{
    [tblview addPullToRefreshWithActionHandler:^{
        
        int64_t delayInSeconds = 2.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            
            [self pull_refresh:@"upperID"];
            [tblview reloadData];
            [tblview.pullToRefreshView stopAnimating];
            
        });
    }];
    
    [tblview addInfiniteScrollingWithActionHandler:^{
        int64_t delayInSeconds = 2.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self pull_refresh:@"lowerID"];
            [tblview reloadData];
            [tblview.infiniteScrollingView stopAnimating];
        });
    }];
    
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //add searchbar delegate
    searchBar.delegate = (id)self;

    
    self.dataSource = [NSMutableArray array];
    // Do any additional setup after loading the view from its nib.
    listOfItems = [[NSMutableArray alloc] init];
    ARC_DB * DB = [[ARC_DB alloc]init];
    if ([DB isHasNewBookDB])
    {
        if ([DB internetConnected])
        {
            [self pull_refresh:@"upperID"];
            //[tblview reloadData];
        }
        arrListNewBook = [DB getNewBook];
    }
    else
    {
        [self refresh];
    }
    NSArray *arrGroup1 =arrListNewBook;
    NSDictionary *dictGroup1 = [NSDictionary dictionaryWithObject:arrGroup1 forKey:@"GroupItem"];
   [listOfItems addObject:dictGroup1];
   [self addPullToRefreshToTable];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(isFiltered)
    {
        return [filteredArrListNewBook count];
    }
    else
    {
        return [arrListNewBook count];
    }
}




- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * section = [NSString stringWithFormat:@"%d", indexPath.section];
    NSString * row = [NSString stringWithFormat:@"%d", indexPath.row];
    for (UIView *view in [self.view subviews])
    {
        [view removeFromSuperview];
    }
    
    NSDictionary*dicForEachRow2;
    if(isFiltered)
    {
        dicForEachRow2 = [filteredArrListNewBook objectAtIndex:indexPath.row];
    }
    else
    {
        dicForEachRow2 = [arrListNewBook objectAtIndex:indexPath.row];
    }
    
    arcAssignDetailEGAViewController *_arcAssignDetailEGAViewController  = [arcAssignDetailEGAViewController alloc];
    
    ARC_DB * DB = [[ARC_DB alloc]init];
    [DB saveBookStatus:[dicForEachRow2 objectForKey:@"ID"]];

    _arcAssignDetailEGAViewController.Doc_Subject=[dicForEachRow2 objectForKey:@"Doc_Subject"];
    _arcAssignDetailEGAViewController.DocToName=[dicForEachRow2 objectForKey:@"DocToName"];
    _arcAssignDetailEGAViewController.Org_Name=[dicForEachRow2 objectForKey:@"Org_Name"];
    _arcAssignDetailEGAViewController.Doc_Register=[dicForEachRow2 objectForKey:@"Doc_Register"];
    _arcAssignDetailEGAViewController.Doc_Serial=[dicForEachRow2 objectForKey:@"Doc_Serial"];
    _arcAssignDetailEGAViewController.Doc_date=[dicForEachRow2 objectForKey:@"Doc_date"];
    _arcAssignDetailEGAViewController.empEmail=[dicForEachRow2 objectForKey:@"empEmail"];
    _arcAssignDetailEGAViewController.Doc_Description=[dicForEachRow2 objectForKey:@"Doc_Description"];
    _arcAssignDetailEGAViewController.ID=[dicForEachRow2 objectForKey:@"ID"];
    _arcAssignDetailEGAViewController.taskDetail=[dicForEachRow2 objectForKey:@"taskDetail"];
    _arcAssignDetailEGAViewController.chkAssign=[dicForEachRow2 objectForKey:@"chkAssign"];
    _arcAssignDetailEGAViewController.Doc_Priority_Name=[dicForEachRow2 objectForKey:@"Doc_Priority_Name"];
    _arcAssignDetailEGAViewController.DocPriorityID=[dicForEachRow2 objectForKey:@"DocPriorityID"];
    _arcAssignDetailEGAViewController.startDate=[dicForEachRow2 objectForKey:@"startDate"];
    _arcAssignDetailEGAViewController.endDate=[dicForEachRow2 objectForKey:@"endDate"];
    _arcAssignDetailEGAViewController.IsDueDate=[dicForEachRow2 objectForKey:@"IsDueDate"];
    _arcAssignDetailEGAViewController.Doc_ReceiveDate=[dicForEachRow2 objectForKey:@"Doc_ReceiveDate"];
    
    _arcAssignDetailEGAViewController.DocBookBeforeSign_ID=[dicForEachRow2 objectForKey:@"DocBookBeforeSign_ID"];
    _arcAssignDetailEGAViewController.DocBookBeforeSign_Name=[dicForEachRow2 objectForKey:@"DocBookBeforeSign_Name"];
    _arcAssignDetailEGAViewController.DocAttachment_ID=[dicForEachRow2 objectForKey:@"DocAttachment_ID"];
    _arcAssignDetailEGAViewController.DocAttachment_Name=[dicForEachRow2 objectForKey:@"DocAttachment_Name"];

    
//    NSLog([dicForEachRow2 objectForKey:@"DocBookBeforeSign_ID"]);
//    NSLog([dicForEachRow2 objectForKey:@"DocBookBeforeSign_Name"]);
//    NSLog([dicForEachRow2 objectForKey:@"DocAttachment_ID"]);
//    NSLog([dicForEachRow2 objectForKey:@"DocAttachment_Name"]);


    
    _arcAssignDetailEGAViewController.accessibilityLabel = [section stringByAppendingString:row];
    [self.view addSubview:_arcAssignDetailEGAViewController.view];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    cell = [[UITableViewCell alloc]init];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle : UITableViewCellStyleSubtitle
                                      reuseIdentifier : @"Cell"];
    }
    
    
    //set dict
    NSDictionary*dicForEachRow;
    if(isFiltered)
    {
        dicForEachRow = [filteredArrListNewBook objectAtIndex:indexPath.row];
    }
    else
    {
        dicForEachRow = [arrListNewBook objectAtIndex:indexPath.row];
    }
    
    
    //image and font
    UIImageView *imgFolder=[[UIImageView alloc]initWithFrame:CGRectMake(0,0,41,41)];

    
    if (([[dicForEachRow objectForKey:@"isOpen"] isEqualToString:@"1"]) )
    {
        imgFolder.image=[UIImage imageNamed:@"letter_open.png"];
    }
    else if (([[dicForEachRow objectForKey:@"isOpen"] isEqualToString:@"0"]) )
    {
        imgFolder.image=[UIImage imageNamed:@"letter_close.png"]; 
    }

    
    //label
    UILabel *lblFrom     =[[UILabel alloc]initWithFrame:CGRectMake(65,20,520,30)];
    UILabel *lblDateGet     =[[UILabel alloc]initWithFrame:CGRectMake(610,10,200,30)];
    UILabel *lbltitle  =[[UILabel alloc]initWithFrame:CGRectMake(65,50,520,30)];
    cell.imageView.image=imgFolder.image;   
    
    
    ////////////////////date
    
    
    
    
    

    NSString *str = [dicForEachRow objectForKey:@"Doc_ReceiveDate"];
    
    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [dateFormatter dateFromString: str];
    
    dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormatter setDateFormat:@"dd/MM/yyyy"];
    NSString *convertedString = [dateFormatter stringFromDate:date];
    
    EGAUtility * Util = [[EGAUtility alloc]init];
    convertedString=[Util getDateTh:(str)];

    NSString *Doc_Subject=[dicForEachRow objectForKey:@"Doc_Subject"];
    NSString *Doc_Priority_ID=[dicForEachRow objectForKey:@"Doc_Priority_ID"];

    
    //add image
    if ([Doc_Priority_ID isEqualToString:@"1"])
    {
        UIImageView * ivPriority = [[UIImageView alloc]initWithFrame:CGRectMake(640,45,40,40)];
        UIImage *img = [UIImage imageNamed:@"flag_yellow.png"];
        [ivPriority setImage:img];
        [cell.contentView addSubview:ivPriority];
    }
    if ([Doc_Priority_ID isEqualToString:@"2"])
    {
        UIImageView * ivPriority = [[UIImageView alloc]initWithFrame:CGRectMake(640,45,40,40)];
        UIImage *img = [UIImage imageNamed:@"flag_red.png"];
        [ivPriority setImage:img];
        [cell.contentView addSubview:ivPriority];
    }
    if ([Doc_Priority_ID isEqualToString:@"3"])
    {
        UIImageView * ivPriority = [[UIImageView alloc]initWithFrame:CGRectMake(640,45,40,40)];
        UIImage *img = [UIImage imageNamed:@"flag_red.png"];
        [ivPriority setImage:img];
        [cell.contentView addSubview:ivPriority];
    }
    if ([Doc_Priority_ID isEqualToString:@"4"])
    {
        UIImageView * ivPriority = [[UIImageView alloc]initWithFrame:CGRectMake(640,45,40,40)];
        UIImage *img = [UIImage imageNamed:@"flag_red.png"];
        [ivPriority setImage:img];
        [cell.contentView addSubview:ivPriority];
    }
    
    
    lblFrom.text = [NSString stringWithFormat:@"จาก : %@", [dicForEachRow objectForKey:@"Org_Name"]];
    lbltitle.text=Doc_Subject;
    
    lblFrom.font = [UIFont systemFontOfSize:22];
    lbltitle.font = [UIFont systemFontOfSize:20];
    lblDateGet.text=convertedString;
    lblDateGet.font = [UIFont systemFontOfSize:20];
    
    lblFrom.textColor = [UIColor darkGrayColor];
    lbltitle.textColor = [UIColor darkGrayColor];
    lblDateGet.textColor = [UIColor darkGrayColor];


    [cell.contentView addSubview:lblFrom];
    [cell.contentView addSubview:lbltitle];
    [cell.contentView addSubview:lblDateGet];
    
    return cell;
}







-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
    if(text.length == 0)
    {
        isFiltered = FALSE;
    }
    else
    {
        isFiltered = TRUE;
        filteredArrListNewBook = [[NSMutableArray alloc] init];
        
        for (NSDictionary*dicForEachRow in arrListNewBook)
        {
            NSRange rangeFrom = [[dicForEachRow objectForKey:@"Org_Name"] rangeOfString:text options:NSCaseInsensitiveSearch];
            NSRange rangeName = [[dicForEachRow objectForKey:@"Doc_Subject"] rangeOfString:text options:NSCaseInsensitiveSearch];
            if(rangeName.location != NSNotFound || rangeFrom.location != NSNotFound)
            {
                [filteredArrListNewBook addObject:dicForEachRow];
            }
        }
    }
    
    [tblview reloadData];
}






- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)dealloc {
    [super dealloc];
}

@end
